<template>
  <div class="containerWrapper">
    <div class="actionBtn" v-if="counter.isShowActionBtn(props.info)">
      <el-button type="info" plain>已选 {{selectArr.length}} 条</el-button>
      <el-button type="primary" @click="handleClick(1)">新增排课</el-button>
      <el-button @click="handleClick(2)" :disabled="!selectArr.length">批量修改</el-button>
      <el-button type="danger" plain @click="handleClick(3)" :disabled="!selectArr.length">删除排课</el-button>
      <el-button @click="handleClick(4)">导出排课</el-button>
    </div>
    <el-table :data="teachingSchedule" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="date" label="排课节数" width="80">
        <template #default="scope">
          第{{scope.$index+1}}节
        </template>
      </el-table-column>
      <el-table-column prop="name" label="报送人社" width="120">
        <template #default="scope">
          <el-switch @change="handleSubmit(scope.row)" v-model="scope.row.isSubmit" :active-value="1" :inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="name" label="关联课程" min-width="380" show-overflow-tooltip>
        <template #default="scope">
          <courseQuery v-model="scope.row.curriculumId" readonly="1" v-if="scope.row.curriculumId"></courseQuery>
          <courseQuery v-model="props.info.curriculumId" readonly="1" v-else></courseQuery>
        </template>
      </el-table-column> -->
      <el-table-column prop="date" label="排课日期" width="170">
        <template #default="scope">
          {{scope.row.date}}（{{getWeekday(scope.row.date)}}）
        </template>
      </el-table-column>
      <el-table-column prop="address" label="上课时间" width="150">
        <template #default="scope">
          {{scope.row.classStartTime}} - {{scope.row.classEndTime}}
        </template>
      </el-table-column>
      <el-table-column prop="unitClassHours" label="课时" width="80" />
      <el-table-column prop="address" label="授课地点" width="200" show-overflow-tooltip>
        <template #default="scope">
          <dictSelect readonly="1" v-model="scope.row.classAddress" dictCode="teaching_location"></dictSelect>
        </template>
      </el-table-column>
      <el-table-column prop="teachingTeacher" label="授课老师" width="120">
        <template #default="scope">
          {{ scope.row.teachingTeacher?scope.row.teachingTeacher:props.info.teachingTeacher}}
        </template>
      </el-table-column>
      <el-table-column prop="teachingContent" label="授课内容" min-width="350" show-overflow-tooltip />
      <el-table-column prop="address" label="班级老师" width="100">
        <template #default="scope">
          <accountSelect v-if="scope.row.classTeacherId" v-model="scope.row.classTeacherId" readonly="1"></accountSelect>
          <accountSelect v-else v-model="props.info.classTeacherId" readonly="1"></accountSelect>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="90" v-if="counter.isShowActionBtn(props.info)">
        <template #default="scope">
          <el-button type="primary" text @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 排课编辑 -->
    <el-drawer v-model="dialogVisible" :title="`${formInline._id? '编辑' : '新增'}排课信息`" size="500" :before-close="handleClose">
      <el-form :model="formInline" label-width="80">
        <!-- <el-form-item label="授课天次">
          <el-input type="number" v-model="formInline.sort" placeholder="授课天次" clearable />
        </el-form-item> -->
        <el-form-item label="关联课程">
          <courseQuery v-model="formInline.curriculumId" :disabled="true"></courseQuery>
        </el-form-item>
        <el-form-item label="排课日期">
          <dateSelectPicker mode="single" v-model="formInline.date"></dateSelectPicker>
        </el-form-item>
        <el-form-item label="上课时间">
          <TimeRange format="HH:mm" v-model:start="formInline.classStartTime" v-model:end="formInline.classEndTime"></TimeRange>
        </el-form-item>
        <el-form-item label="单位课时">
          <el-select v-model="formInline.unitClassHours" placeholder="单位课时">
            <el-option v-for="item in unitClassHoursList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课讲师">
          <el-input v-model="formInline.teachingTeacher" placeholder="授课讲师" clearable />
        </el-form-item>
        <el-form-item label="授课地点">
          <dictSelect v-model="formInline.classAddress" dictCode="teaching_location"></dictSelect>
        </el-form-item>
        <el-form-item label="班级老师">
          <accountSelect v-model="formInline.classTeacherId" :disabled="true"></accountSelect>
        </el-form-item>
        <el-form-item label="授课内容">
          <el-input :autosize="{ minRows: 4 }" type="textarea" v-model="formInline.teachingContent" placeholder="授课内容" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="subimit">
            确 认
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 批量编辑 -->
    <teachingScheduleBatchAction ref="teachingScheduleBatchActionRef" @fatherMethod="loadData"></teachingScheduleBatchAction>

    <!-- 新增排课 -->
    <updateClass ref="updateClassRef" @fatherMethod="loadData"></updateClass>
  </div>
</template>

<script setup lang="ts">
//counter
import useCounterStore from "@/store/counter";
const counter = useCounterStore();

import updateClass from "@/views/courseManage/components/updateClass.vue";
import teachingScheduleBatchAction from "@/views/courseManage/components/teachingScheduleBatchAction.vue";
const { proxy } = getCurrentInstance();
let props = defineProps(["info"]);
const emit = defineEmits(["fatherMethod"]);
//emit("fatherMethod"); //列表重新加载

let teachingSchedule = ref([]);
let unitClassHoursList = ref([2, 4, 6, 8, 10]);
let dialogVisible = ref(false);
let formInline = ref({
  sort: null,
  curriculumId: "",
  date: "",
  classStartTime: "",
  classEndTime: "",
  unitClassHours: "",
  classAddress: "",
  teachingTeacher: "",
  teachingContent: "",
  classTeacherId: "",
});
let selectArr = ref([]); //选中的排课数据

//是否报送人设
async function handleSubmit(e) {
  await proxy.$apis.teachingScheduleData({
    type: "update",
    data: e,
  });
  loadData();
}

//保存排课
async function save() {
  let data = { ...formInline.value };
  data.dateStamp = proxy.$utils.getTimeFn(formInline.value.date); //开课时间的时间戳
  data.classId = props.info._id;
  //编辑
  if (data._id) {
    await proxy.$apis.teachingScheduleData({
      type: "update",
      data,
    });
  } else {
    let { date } = data;
    let index = proxy.$utils.findIndexByField(
      teachingSchedule.value,
      "date",
      date
    );
    if (index != -1) return proxy.$utils.showToast("该日期已存在排课", 0);
    await proxy.$apis.teachingScheduleData({
      type: "add",
      data,
    });
  }
}

//删除排课
async function del(_id) {
  await proxy.$apis.teachingScheduleData({
    type: "del",
    data: { _id },
  });
}

async function handleClick(num) {
  switch (num) {
    case 1:
      let newValue = proxy.$utils.deepcopy(props.info);
      delete newValue.unitClassHours;
      delete newValue.classDates;
      delete newValue.classStartTime;
      delete newValue.classEndTime;
      delete newValue.classAddress;
      delete newValue.teachingTeacher;
      proxy.$refs.updateClassRef.open(newValue, "disabledClassInfo");
      break;
    case 2:
      proxy.$refs.teachingScheduleBatchActionRef.open(selectArr.value);
      break;
    case 3: //删除排课
      let resp = await proxy.$utils.confirmTips("确认删除选中的排课数据?");
      if (!resp) return;
      for (let index = 0; index < selectArr.value.length; index++) {
        const element = selectArr.value[index];
        await del(element);
      }
      proxy.$utils.showToast("删除成功");
      loadData();
      break;
    case 4:
      console.log("导出排课", teachingSchedule.value);
      let list = [];

      teachingSchedule.value.forEach((element, index) => {
        list.push({
          排课节数: `第${index + 1}节`,
          //关联课程: element.curriculumId,
          排课日期: element.date,
          上课时间: element.classStartTime + " - " + element.classEndTime,
          课时: element.unitClassHours,
          授课地点: element.classAddress,
          授课老师: element.teachingTeacher
            ? element.teachingTeacher
            : props.info.teachingTeacher,
          授课内容: element.teachingContent,
          //班级老师: element.classTeacherId,
        });
      });
      let cols = []; //设置表头样式
      list.forEach((element) => {
        cols.push({ wch: 20 });
      });
      let query = {
        jsonData: list,
        cols,
      };
      await proxy.$utils.exportToExcel(query, "排课信息");
      break;
    default:
      break;
  }
}

async function subimit() {
  await save();
  proxy.$utils.showToast("操作成功");
  handleClose();
}

function handleEdit(row) {
  formInline.value = proxy.$utils.formatFunction(row, { ...formInline.value });
  if (!formInline.value.classTeacherId)
    formInline.value.classTeacherId = props.info.classTeacherId;
  if (!formInline.value.curriculumId)
    formInline.value.curriculumId = props.info.curriculumId;
  formInline.value._id = row._id;
  dialogVisible.value = true;
}

function handleClose() {
  formInline.value = {
    sort: null,
    curriculumId: "",
    date: "",
    classStartTime: "",
    classEndTime: "",
    unitClassHours: "",
    classAddress: "",
    teachingTeacher: "",
    teachingContent: "",
    classTeacherId: "",
  };
  loadData();
  dialogVisible.value = false;
}

async function loadData() {
  let newValue = proxy.$utils.deepcopy(props.info);
  let arr = await proxy.$apis.teachingScheduleData({
    type: "query",
    data: { classId: newValue._id },
  });
  if (arr && arr.length) {
    teachingSchedule.value = arr;
  } else {
    let { classDates } = newValue;
    if (classDates) {
      //新增排课
      for (let index = 0; index < classDates.length; index++) {
        const element = classDates[index];
        let dataJson = {
          classId: newValue._id,
          date: element,
          dateStamp: proxy.$utils.getTimeFn(element), //开课时间的时间戳
          //curriculumId: newValue.curriculumId,
          classStartTime: newValue.classStartTime,
          classEndTime: newValue.classEndTime,
          unitClassHours: newValue.unitClassHours,
          classAddress: newValue.classAddress,
          teachingTeacher: newValue.teachingTeacher,
          teachingContent: "",
          //classTeacherId: newValue.classTeacherId,
        };
        await proxy.$apis.teachingScheduleData({
          type: "add",
          data: dataJson,
        });
      }
      loadData();
    }
  }
}

function getWeekday(date) {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const weekday = new Date(date).getDay();
  return weekdays[weekday];
}

function handleSelectionChange(val) {
  let arr = [];
  val.forEach((element) => {
    arr.push(element._id);
  });
  selectArr.value = arr;
}

watch(
  () => props.info,
  (newValue, oldValue) => {
    if (newValue) loadData();
  },
  { deep: true, immediate: true }
);
</script>



<style lang="scss" scoped>
.actionBtn {
  margin-bottom: 20px;
}
</style>